package com.da.lon.wang.xlg.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.activity.EditAddressActivity;
import com.da.lon.wang.xlg.activity.LoginActivity;
import com.da.lon.wang.xlg.activity.OrderActivity;
import com.da.lon.wang.xlg.activity.TakeTypeChoiseActivity;
import com.da.lon.wang.xlg.activity.WebViewActivity;
import com.da.lon.wang.xlg.bean.CheckBean;
import com.da.lon.wang.xlg.bean.OrderInfoResultBean;
import com.da.lon.wang.xlg.bean.TakeGoodsTypeBean;
import com.da.lon.wang.xlg.bean.TakeTypeIdsBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.view.ProductsPopupWindow;
import com.da.lon.wang.xlg.view.ProductsPopupWindow.CallBack3;
import com.da.lon.wang.xlg.view.ProductsShowMessagesPopupWindow;

import net.tsz.afinal.http.AjaxParams;

public class BuyUtil {

    Context context;
    DialogUtil dialogUtil;
    private ProductsShowMessagesPopupWindow productsShowMessagesPopupWindow;

    public BuyUtil(Context context) {
        this.context = context;
        dialogUtil = new DialogUtil(context);
    }

    /**
     * 立即购买按钮点击事件
     *
     * @param send_address_id
     * @param is_seckill      是否是秒杀
     */
    public void buyClick(String pid, String value, String attr,
                         boolean isCoffee, String send_address_id, String kefu_phone,
                         View ouka_products_bottom, PopupWindow products_popupWindow,
                         CallBack3 myCallBack) {

        if (TextUtils.isEmpty(MyApplication.getUserKey())) {
            // 未登录
            Intent intent = new Intent(context, LoginActivity.class);
            intent.putExtra("isGotoHome", false);
            context.startActivity(intent);
        } else {
            TypeChoise(pid, value, attr, isCoffee, send_address_id, kefu_phone,
                    ouka_products_bottom, products_popupWindow, myCallBack);

        }
    }

    /**
     * 加入购物车
     *
     * @param send_address_id
     */
    private void TypeChoise(String pid, String value, String attr,
                            final boolean isCoffee, String send_address_id,
                            final String kefu_phone, final View ouka_products_bottom,
                            final PopupWindow products_popupWindow, final CallBack3 myCallBack) {
        String count = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.COUNT_NUMBER, "");
        try {

            if (!"".equals(count)) {

                String url = XLGConstants.URL + XLGConstants.URL_CART_HRAD
                        + "AjaxAdd";
                HttpLoader<TakeGoodsTypeBean> httpLoader = new HttpLoader<TakeGoodsTypeBean>(
                        context, url, TakeGoodsTypeBean.class, 15 * 1000);
                AjaxParams params = new AjaxParams();
                params.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                        + "AjaxAdd"));
                params.put("id", MyApplication.getUserId());
                params.put("pid", pid);
                params.put("type", "3");
                params.put("user_key", MyApplication.getUserKey());
                params.put("count", count);
                params.put("value", value);
                params.put("products_model_attr", attr);
                params.put("fhtype", send_address_id);
                httpLoader.loadData(params);

                httpLoader
                        .setManagerListener(new OnWebLoadListener<TakeGoodsTypeBean>() {

                            @Override
                            public void OnStart() {
                                dialogUtil.showDialog();
                            }

                            @Override
                            public void OnError(String error) {
                                dialogUtil.dismissDialog();
                            }

                            @Override
                            public void onSuccess(TakeGoodsTypeBean t) {
                                dialogUtil.dismissDialog();
                                if (t != null && "000000".equals(t.getCode())) {
                                    TakeTypeIdsBean bean = t.getResult();
                                    if (bean != null) {
                                        String ids = bean.getIds();
                                        if (isCoffee) {
                                            buyCoffee(ids);
                                        } else {
                                            getTakeGoodsType(ids,
                                                    bean.getNeedCoordinates());
                                        }
                                        if (products_popupWindow != null) {
                                            products_popupWindow.dismiss();
                                        }
                                    }
                                } else if (t != null
                                        && "000002".equals(t.getCode())
                                        && t.getMessage().contains("库存不足")) {
                                    closeShowMessagesPopupWindow();
                                    productsShowMessagesPopupWindow = new ProductsShowMessagesPopupWindow(
                                            context, kefu_phone, myCallBack);
                                    // 显示窗口
                                    productsShowMessagesPopupWindow
                                            .showAtLocation(
                                                    ouka_products_bottom,
                                                    Gravity.CENTER
                                                            | Gravity.CENTER_HORIZONTAL,
                                                    0, 0);
                                } else {
                                    ToastUtils.showShort(context,
                                            t.getMessage());
                                }
                            }
                        });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 购买咖啡
     *
     * @param ids
     */
    public void buyCoffee(String ids) {
        try {

            HttpLoader<CheckBean> loader2 = new HttpLoader<CheckBean>(context,
                    XLGConstants.URL + "Cart-checkout", CheckBean.class,
                    60 * 1000);

            AjaxParams params11 = new AjaxParams();

            params11.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                    + "checkout"));
            params11.put("user_key", MyApplication.getUserKey());
            params11.put("id", MyApplication.getUserId());
            params11.put("ids", ids);

            params11.put("addid", "1");
            params11.put("area_type", "1");
            params11.put("version", "21");
            params11.put("data_store", "1");
            // params11.put("qt", "1");

            loader2.setManagerListener(new OnWebLoadListener<CheckBean>() {

                @Override
                public void OnStart() {
                }

                @Override
                public void OnError(String error) {
                }

                @Override
                public void onSuccess(CheckBean t) {
                    if (t != null && t.getCode().equals("000000")) {
                        Intent intent = new Intent(context,
                                WebViewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("url", t.getResult());
                        bundle.putInt("flag", 1800);
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    } else {
                        Toast.makeText(context, t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

            loader2.loadData(params11);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 确定提货方式
     *
     * @param ids
     */
    public void getTakeGoodsType(final String ids, final String needCoordinates) {
        try {

            if (ids != null && !"".equals(ids)) {
                String url = XLGConstants.URL + XLGConstants.URL_CART_HRAD
                        + XLGConstants.URL_CHOISE;
                HttpLoader<OrderInfoResultBean> loder = new HttpLoader<OrderInfoResultBean>(
                        context, url, OrderInfoResultBean.class);
                AjaxParams params = new AjaxParams();
                params.put(
                        "token",
                        XLGDataUtils.encrypt2MD5("Cart" + XLGConstants.SECRET
                                + XLGConstants.URL_CHOISE));
                params.put("id", MyApplication.getUserId());
                params.put("user_key", MyApplication.getUserKey());
                params.put("ids", ids);
                params.put("needCoordinates", needCoordinates);
                loder.loadData(params);
                loder.setManagerListener(new OnWebLoadListener<OrderInfoResultBean>() {

                    @Override
                    public void OnStart() {
                        dialogUtil.showDialog();
                    }

                    @Override
                    public void OnError(String error) {
                        dialogUtil.dismissDialog();
                    }

                    @Override
                    public void onSuccess(OrderInfoResultBean t) {
                        dialogUtil.dismissDialog();
                        if (t != null && "000000".equals(t.getCode())) {
                            if (t.getResult() != null) {
                                Intent intent = null;
                                Bundle bundle = new Bundle();
                                bundle.putString("ids", ids);
                                bundle.putString("needCoordinates",
                                        needCoordinates);
                                if ("1".equals(t.getResult().getIs_dw())) {
                                    // 跳转到选择店铺界面
                                    intent = new Intent(context,
                                            TakeTypeChoiseActivity.class);
                                    intent.putExtras(bundle);
                                } else if ("0".equals(t.getResult().getIs_dw())) {
                                    // 跳转到确定订单界面
                                    intent = new Intent(context,
                                            OrderActivity.class);
                                    intent.putExtras(bundle);
                                }
                                context.startActivity(intent);
                            }
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前位置的经纬度
     *
     * @return 数组的第一个数是经度 第二个数是纬度
     */
    public double[] getCoordinates() {
        double[] result = new double[2];
        double latitude = 0.0;
        double longitude = 0.0;
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        String provider = getProvider(locationManager);
        Location location = null;
        if (provider != null) {
            location = locationManager.getLastKnownLocation(provider);
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                result[0] = latitude;
                result[1] = longitude;
            }
        }
        LocationListener locationListener = new LocationListener() {
            @Override
            public void onStatusChanged(String provider, int status,
                                        Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onLocationChanged(Location location) {
            }
        };
        for (int i = 0; location == null && i < 3; i++) {
            if (provider != null) {
                locationManager.requestLocationUpdates(provider, 1000, 0,
                        locationListener);
                location = locationManager.getLastKnownLocation(provider);
                if (location != null) {
                    latitude = location.getLatitude(); // 经度
                    longitude = location.getLongitude(); // 纬度
                    result[0] = latitude;
                    result[1] = longitude;
                }
            }
        }
        return result;
    }

    /**
     * 设置GPS的属性 包括精确度,是否忽略海拔等
     *
     * @param locationManager
     * @return
     */
    private String getProvider(LocationManager locationManager) {
        // TODO Auto-generated method stub
        // 构建位置查询条件
        Criteria criteria = new Criteria();
        // 查询精度：高
        criteria.setAccuracy(2);
        // 是否查询海拨：否
        criteria.setAltitudeRequired(false);
        // 是否查询方位角 : 否
        criteria.setBearingRequired(false);
        // 是否允许付费：是
        criteria.setCostAllowed(true);
        // 电量要求：低
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        // 返回最合适的符合条件的 provider ，第 2 个参数为 true 说明 , 如果只有一个 provider 是有效的 , 则返回当前
        // provider
        return locationManager.getBestProvider(criteria, true);
    }

    /**
     * 关闭弹出窗
     */
    public void closeShowMessagesPopupWindow() {
        if (productsShowMessagesPopupWindow != null
                && productsShowMessagesPopupWindow.isShowing()) {
            productsShowMessagesPopupWindow.dismiss();
        }
    }

    /**
     * 秒杀购物流程
     *
     * @param is_card
     */
    public void buyClickForSeckill(String product_number, int store_id, int is_card, String value,
                                   String attr, boolean isCoffee, String send_address_id,
                                   View ouka_products_bottom,
                                   ProductsPopupWindow products_popupWindow, CallBack3 myCallBack) {
        if (TextUtils.isEmpty(MyApplication.getUserKey())) {
            // 未登录
            Intent intent = new Intent(context, LoginActivity.class);
            context.startActivity(intent);
        } else {
            // 已登录 秒杀流程
            seckillMakeOrder(product_number, store_id, is_card, value, attr, isCoffee,
                    send_address_id, ouka_products_bottom,
                    products_popupWindow, myCallBack);
        }
    }

    /**
     * 秒杀下单
     *
     * @param is_card
     * @param send_address_id
     */
    private void seckillMakeOrder(String product_number, int store_id, final int is_card, String value,
                                  String attr, boolean isCoffee, String send_address_id,
                                  View ouka_products_bottom, PopupWindow products_popupWindow,
                                  CallBack3 myCallBack) {
        try {
            HttpLoader<CheckBean> loader2 = new HttpLoader<CheckBean>(context,
                    XLGConstants.URL + "ActivitySeckill-spikeProcessing",
                    CheckBean.class, 60 * 1000);

            AjaxParams params = new AjaxParams();

            params.put("token", XLGDataUtils.encrypt2MD5("ActivitySeckill"
                    + "2015#$%" + "spikeProcessing"));
            params.put("id", MyApplication.getUserId());

            params.put("shop_id", String.valueOf(store_id));
            params.put("fhtype", send_address_id);
            params.put("attr_id", attr);
            params.put("product_number", product_number);

            loader2.setManagerListener(new OnWebLoadListener<CheckBean>() {

                @Override
                public void OnStart() {
                }

                @Override
                public void OnError(String error) {
                }

                @Override
                public void onSuccess(CheckBean t) {
                    if (t != null && t.getCode().equals("000000")) {
                        Intent intent = new Intent(context,
                                WebViewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("url", t.getResult());
                        bundle.putInt("flag", 1800);
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    } else if (t != null && t.getCode().equals("444444")) {
                        Toast.makeText(context, t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                        // 没有收货地址的时候
                        int requestCode = 1;
                        Intent intent11 = new Intent(context,
                                EditAddressActivity.class);
                        // 自动定位
                        intent11.putExtra("key", 0);
                        // 身份证号码 0 为不需要 其他为需要身份证号！
                        intent11.putExtra("pro_type", String.valueOf(is_card));
                        //默认地址  1 为添加为默认地址   0为  不添加为 默认地址
                        intent11.putExtra("defult_address", "1");
                        ((Activity) context).startActivityForResult(intent11, requestCode);
                    } else {
                        Toast.makeText(context, t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });

            loader2.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
